package com.lavida.project.system.papers.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.lavida.common.utils.security.ShiroUtils;
import com.lavida.framework.web.controller.BaseController;
import com.lavida.framework.web.page.TableDataInfo;
import com.lavida.project.common.DownLoadUtils;
import com.lavida.project.system.papers.domain.Papers;
import com.lavida.project.system.papers.service.PapersService;
import com.lavida.project.system.papers.service.SubPapersService;
import com.lavida.project.system.user.domain.User;
import com.lavida.project.system.user.service.IUserService;

@Controller
@RequestMapping("/system/papers")
public class PapersController extends BaseController{
	private String prefix = "system/papers";
	@Autowired
	private PapersService papersService;
	@Autowired
	private IUserService userService;
	@Autowired
	private SubPapersService subPapersService;
	@RequestMapping()
	@RequiresPermissions("data:papers:view")
	public String goods(ModelMap mmap) {
		User user  = ShiroUtils.getSysUser();
		User user1 = userService.selectUserById(user.getUserId());
		mmap.put("user", user1);
		return prefix + "/papers";
	}
	@RequiresPermissions("data:papers:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Papers paper) {
		startPage();		
		 List<Papers> selectPapers = papersService.selectPapers(paper);
		return getDataTable(selectPapers);
	}
	@RequiresPermissions("data:papers:add")
	@RequestMapping("/showAddParper")
	public String showAddParper(Papers paper,MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException {
		 String path=filePath(request);
	     System.out.println("path>>>>>>"+path);
	     String originalFilename=file.getOriginalFilename();
	     String uuid=UUID.randomUUID().toString().replace("-","");
	     String filename=uuid+"_"+originalFilename.replace(" ", "");
	     file.transferTo(new File(path,filename));
	     paper.setAnnex(originalFilename.replace(" ", ""));
	     paper.setAnnexPath(filename.replace(" ", ""));
		 papersService.insertPapers(paper);
		 return "redirect:/system/papers";
	}
	@RequestMapping("/download")
	public void download(String fileRealname,String fileVmname,HttpServletResponse response,HttpServletRequest request) {
        String string=request.getHeader("User-Agent");
        String Uploadfilename=null;
        try {
			Uploadfilename= DownLoadUtils.getFileName(string,fileVmname);
			System.out.println(Uploadfilename);	

	        response.setHeader("Content-disposition","attachment;filename="+Uploadfilename);
	        String fileVmPath=filePath(request);
	        System.out.println(String.format("%s\\%s",fileVmPath,fileRealname));
	        ServletOutputStream s=response.getOutputStream();
	        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(String.format("%s/%s",fileVmPath,fileRealname)));
	        int a;
	        byte[] bytes=new byte[1024];
	        while ((a = bufferedInputStream.read(bytes))!=-1){
	            s.write(bytes,0,a);
	        }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	@RequiresPermissions("data:papers:delete")
	@RequestMapping("/delete")
	@ResponseBody
	public Map<String, String> delete(@RequestParam("ids[]")int[] ids){
		Map<String, String> result = new HashMap<String, String>();
		subPapersService.deleteSubp(ids);
		papersService.deletePapers(ids);
		result.put("msg", "删除成功");
		return result;
	}
	@RequestMapping("/getPapers")
	@ResponseBody
	public Map<String, Object> getPapers(int id){
		Map<String, Object> result = new HashMap<String, Object>();
		Papers papers = papersService.getPapers(id);
		result.put("papers", papers);
		return result;
	}
	@RequiresPermissions("data:papers:update")
	@RequestMapping("/showUpdateParper")
	public String updatePapers(Papers papers,@RequestParam("annex1")MultipartFile file,HttpServletRequest request) throws IllegalStateException, IOException {
		Papers papers2 = papersService.getPapers(papers.getId());
		if(file.isEmpty()) {
			papers.setAnnex(papers2.getAnnex());
			papers.setAnnexPath(papers2.getAnnexPath());
		}else {
			 String path=filePath(request);
		     //System.out.println("path>>>>>>"+path);
		     String originalFilename=file.getOriginalFilename();
		     System.out.println(">>>originalFilename"+originalFilename);
		     System.out.println(">>>originalFilename"+originalFilename.replace(" ", ""));
		     //System.out.println(originalFilename+"=================");
		     String uuid=UUID.randomUUID().toString().replace("-","");
		     String filename=uuid+"_"+originalFilename.replace(" ", "");
		     file.transferTo(new File(path,filename));
		     papers.setAnnex(originalFilename.replace(" ", ""));
		     papers.setAnnexPath(filename.replace(" ", ""));
		}
		papersService.updatePapers(papers);
		return "redirect:/system/papers";		
	}
	 private static String filePath(HttpServletRequest request){
	        // 先获取到要上传的文件目录
	        String path = request.getSession().getServletContext().getRealPath("/annex");
	        
	        // 创建File对象，一会向该路径下上传文件
	        File file = new File(path);
	        // 判断路径是否存在，如果不存在，创建该路径
	        if(!file.exists()) {
	            file.mkdirs();
	        }
	        return path;
	    }
}